package cn.lexi.vip.config.security;

import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author Aaron
 */

public class CsrfHeaderFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        CsrfToken csrfToken = (CsrfToken) request.getAttribute(CsrfToken.class.getName());

        if (csrfToken != null) {
            String token = csrfToken.getToken();
            Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
            if (noCookieSetYet(cookie) || isIncorrectToken(token, cookie)) {
                genCSRFToken(response, token);
            }
        }

        filterChain.doFilter(request, response);
    }

    private void genCSRFToken(HttpServletResponse response, String token) {
        Cookie cookie;
        cookie = new Cookie("XSRF-TOKEN", token);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    private boolean isIncorrectToken(String token, Cookie cookie) {
        return token != null && !token.equals(cookie.getValue());
    }

    private boolean noCookieSetYet(Cookie cookie) {
        return cookie == null;
    }
}
